package com.hj.ipproxy.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TrustSSL {
	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
	
	public static X509TrustManager getTrustAnyTrustManager(){
		return new TrustAnyTrustManager();
	}
	
	public static HostnameVerifier getHostnameVerifier(){
		return new TrustAnyHostnameVerifier();
	}

	public static String dopost(String url,String ip) throws Exception {
		InputStream in = null;
		BufferedReader reader = null;
		StringBuffer html = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
					new java.security.SecureRandom());
			URL console = new URL(url);
			Proxy typeProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, 8080));
			HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(typeProxy);
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(2500);
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:33.0) Gecko/20100101 Firefox/33.0");
			conn.connect();
			in = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
			html = new StringBuffer();
			for (String line; (line=reader.readLine()) != null;) {
				html.append(line).append("ln");
			}
			conn.disconnect();
		} catch (ConnectException e) {
			System.out.println("ConnectException");
			System.out.println(e);
			throw e;

		} catch (IOException e) {
			System.out.println("IOException");
			System.out.println(e);
			throw e;

		} finally {
			try {
				if (in != null) {in.close();
				}
				if (reader != null) {reader.close();
				}
			} catch (Exception e) {
			}
		}
		return html.toString();
	}
}
